import Vue from 'vue'
import VueRouter from 'vue-router'
// 引入路由配置
import routes from './routes'
Vue.use(VueRouter)
// 仓库
import store from '@/store'

//编程式导航 路由跳转到当前路由(参数不变), 多次执行会抛出NavigationDuplicated的警告错误 的解决
//把人家原型对象的push方法进行保存
let originPush = VueRouter.prototype.push
let originReplace = VueRouter.prototype.replace

VueRouter.prototype.push = function (location, resolve, reject) {
  //面试:函数apply与call区别?
  //相同的地方:都可以篡改函数里面this
  //不同的地方:apply传递参数 数组  call传递参数 逗号分割

  if (resolve && reject) {
    originPush.call(this, location, resolve, reject)
  } else {
    //当前函数this：即为VueRouter类的实例
    //originPush 方法里面this，是windows
    //利用人家push方法实现路由跳转，保证push里面this,应该vueRouter类的实例
    originPush.call(
      this,
      location,
      () => {},
      () => {}
    )
  }
}

VueRouter.prototype.replace = function (location, resolve, reject) {
  if (resolve && reject) {
    originReplace.call(this, location, resolve, reject)
  } else {
    originReplace.call(
      this,
      location,
      () => {},
      () => {}
    )
  }
}

const router = new VueRouter({
  base:'/sph/',
  routes,
  scrollBehavior(to, from, savedPosition) {
    // 始终滚动到顶部
    return { y: 0 }
  }
})

// 导航守卫
router.beforeEach(async (to, from, next) => {
  const token = store.state.user.token
  const userInfo = store.state.user.userInfo
  // 有token 登录过
  if (token) {
    // 有用户信息--token没有失效
    if (userInfo.name) {
      //登录过,不能再去登录页
      if (to.path == '/login') {
        alert('你已经登录了')
      } else {
        next()
      }
    } else {
      // 尝试同步请求用户信息,有可能是刚刚刷新,vuex仓库用户信息没有请求好
      let res = await store.dispatch('getUserInfo')
      if (res.ok) {
        next()
      } else {
        //token确定失效,从新登录
        // 清除token再跳转
        alert('登录已过期,请重新登录')
        store.dispatch('logout')
        next('/login')
      }
    }
  }
  // 无token 没登陆
  else {
    if (to.path == '/trade') {
      alert('请先登录!')
      // 跳转登录页
      next('/login?redirect=/trade')
    } else if (to.path.indexOf('/center') != -1) {
      alert('请先登录!')
      // 跳转登录页
      next('/login?redirect=/center')
    } else if (to.path.indexOf('/pay') != -1) {
      alert('请先登录!')
    } else {
      next()
    }
  }
})

export default router
